import {AfterViewInit, Component, OnInit, ViewChild} from '@angular/core';
import {OneOperationComponent} from '../../../widgets/one-operation/one-operation.component';
import {ActivatedRoute, Router} from '@angular/router';
import {PageSubject} from '../../../util/page-subject';
import {OneDialogService} from '../../../widgets/one-dialog/one-dialog.service';
import {ResponseUtil} from '../../../util/response-util';
import {TableUtil} from '../../../util/table-util';
import {DsService} from "../ds/ds.service";
import {MsgResult} from "../../../models/msg-result";
import {API, MsgConstants} from "../../../constants/constants";
import {DsconfService} from "./dsconf.service";
import {DataAuditAPI} from "../data-audit-constants";
declare  var  $;
@Component({
  selector: 'app-fieldconf',
  templateUrl: './fieldconf.component.html',
  styleUrls: ['./fieldconf.component.css']
})
export class FieldconfComponent implements OnInit, AfterViewInit {
  @ViewChild(OneOperationComponent) operation: OneOperationComponent;
  table: any;

  fieldConf: Array<String> = [];
  // 数据源的选择
  dataSourceArr: Array<any> = [];

  dataSourceId:string = '';

  proxy = {
    'fieldConfAdd': () => this.fieldConfAdd(),
    'fieldConfUpdate': () => this.fieldConfUpdate(),
    'fieldConfDelete': () => this.fieldConfDelete()
  };

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private pageSubject: PageSubject,
    private tableUtil: TableUtil,
    private responseUtil: ResponseUtil,
    private dialogService: OneDialogService,
    private dsConfService: DsconfService,
    private dsService: DsService,
  ) { }

  ngAfterViewInit(): void {
    // 操作函数代理
    this.operation.proxy = this.proxy;
  }
  ngOnInit() {
    this.pushPage();
    this.initData();
    this.loadFieldConf();
  }

  /**
   * 面包屑导航
   */
  private pushPage() {
    this.pageSubject.pushPage('审核字段配置', '查询');
  }

  /**
   * 初始化数据
   */
  private initData() {
    this.dsService.getDataSourceInfos().subscribe(
      result => this.responseUtil.success(result, this.generateDsInfos),
      message => this.responseUtil.error(message)
    );
  }

  /**
   *
   * @param {MsgResult} result
   */
  private generateDsInfos = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {

      // this.dataSourceArr = result.data.dsName
      if (result.data && result.data.length > 0) {
        result.data.forEach((val) => {
          if( val.isUse == '1') {
            this.dataSourceArr.push({
              name: val.dsName,
              value: val.id
            })
          }
        })
      }
      result.data.dsName;
      // console.log("获取数据源"+JSON.stringify(this.dataSourceArr));
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }
  /***
   * 添加数据源配置
   */
  private fieldConfAdd() {
    this.router.navigate(['add'], {relativeTo: this.route})
  }

  /**
   * 修改数据源配置
   */
  private fieldConfUpdate() {
    const  rows = this.table.bootstrapTable('getSelections');
    this.fieldConf = this.tableUtil.getCloumns(rows, 'id')
    if (this.fieldConf.length !== 1) {
      this.dialogService.modalInfo('请选择一条数据')
    } else {
      this.router.navigate(['update', {id: this.fieldConf[0]}], {relativeTo: this.route});
    }
  }

  /**
   * 删除数据源配置
   */
  private fieldConfDelete() {
    const  rows = this.table.bootstrapTable('getSelections');
    this.fieldConf = this.tableUtil.getCloumns(rows, 'id');
    if ( undefined ===  this.fieldConf || this.fieldConf.length ===  0 ) {
      this.dialogService.modalInfo('请选择一条数据');
    } else {
      this.dialogService.modalInfoWithCancelBtn('确定删除？', this.requestDelete);
    }
  }

  /**
   * 对返回结果进行处理
   */
  private requestDelete = () => {
    if (this.fieldConf.length ===  1) {
      this.dsConfService.deleteDsConf(this.fieldConf[0]).subscribe(
        result => this.responseUtil.success(result, this.processDsDeleteResult),
        message => this.responseUtil.error(message)
      );
    } else {
      this.dsConfService.deleteDsConfs(this.fieldConf).subscribe(
        result => this.responseUtil.success(result, this.processDsDeletesResult),
        message => this.responseUtil.error(message)
      );
    }
  };
  /**
   * 单一删除结果处理
   * @param {MsgResult} result
   */
  processDsDeleteResult = (result: MsgResult) => {
    if (result && result.code ===  MsgConstants.MSG_CODE_OK) {
      this.search();
    }
    if (result && result.code !== MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * 批量删除结果处理
   */
  processDsDeletesResult = (result: MsgResult) => {
    if (result && result.code ===  MsgConstants.MSG_CODE_OK) {
      this.search();
    }
    if (result && result.code !== MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * 刷新表格
   */
  search() {
    this.table.bootstrapTable('refresh');
  }

  /**
   * 加载表格
   */
  private loadFieldConf() {
    this.table = this.tableUtil.load('one_table_fieldconf', {
      columns: [
        {checkbox: true },
        {field: 'id', title: 'ID', align: 'left', visible: false , switchable: false},
        {field: 'auditDsName', title: '审核数据源', align: 'left'},
        {field: 'isKeepOri', title: '保持原始', align: 'left', formatter: this.isKeepOri},
        {field: 'isUse' , title: '是否使用', align: 'left' , formatter: this.yesOrNoUse},
        { field: 'creatorName', title: '创建人', align: 'left' , visible: false },
        { field: 'CREATE_DATE' , title: '创建日期', align: 'left', sortName: 'CREATE_DATE', sortable: true , visible: false },
        { field: 'editorName' , title: '修改人', align: 'left', visible: false},
        { field: 'MODIFIED_DATE' , title: '修改日期', align: 'left', visible: false , sortName: 'MODIFIED_DATE', sortable: true},
      ],
      idField: 'id',
      sidePagination: 'server',
      pagination: true,
      pageNumber: 1,
      pageSize: 15,
      pageList: [10, 15, 50],
      paginationPreText: '上一页',
      paginationNextText: '下一页',
      paginationLoop: false, // 是否开启循环分页
      // singleSelect: true,//单选
      singleSelect: false, // 多选
      clickToSelect: true, // 点击选中
      toolbar: '#one_operation_fieldconf', // 表头的操作按钮
      url: DataAuditAPI.dsConfPageListV2,
      method: 'post',
      // 传递附加参数
      queryParams: (params) => {
        params.oriDsId = this.dataSourceId;
        // params.auditDsId = $('#dataSourceId').val();
        params.auditDsName = $('#auditDsName').val();
        return params;
      },
      // 返回数据处理器
      responseHandler: (result) => {
        return this.responseUtil.bsPageHandler(result, (result) => {
          result.data.rows.forEach(function (value) {
            value.CREATE_DATE = value.createDate || '';
            value.MODIFIED_DATE = value.modifiedDate || '';
          });
        });
      },
      height: 700, // table高度
      sortable: true,
      sortorder: 'asc',
      sortName: 'CREATEDATE',  // 默认
      // search:true,//是否显示搜索框
      // searchOnEnterKey:true,//点击enter键是否触发搜索事件
      // searchText:'',//默认搜索内容
      // smartDisplay:true,//智能显示分页或card视图
      showColumns: true, // 显示自定义显示列按钮
      showRefresh: true, // 显示刷新按钮
      minimumCountColumns: 3, // 最少保留显示的列数量
      showToggle: true, // 显示视图切换按钮
      showPaginationSwitch: true, // 显示是否分页切换按钮
      // css
      classes: 'table table-hover',
      striped: true, // 隔行变色
      mobileResponsive: true// 响应式
    });
    this.tableUtil.bindResetTableView(this.table);
  }

  private isKeepOri (value, row, index) {
    if (value ==  '0') {
      return '否';
    }
    if (value == '1') {
      return '是'
    }
  }
  private yesOrNoUse (value, row, index) {
    if (value ==  '0') {
      return '否';
    }
    if (value == '1') {
      return '是'
    }
  }

}
